package com.wtwd.campus.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.wtwd.campus.constant.ManLanguageEnum;
import com.wtwd.campus.dao.SysPermissionMapper;
import com.wtwd.campus.entity.SysPermission;
import com.wtwd.campus.service.SysPermissionService;
import com.wtwd.campus.utils.TreeUtil;
import com.wtwd.campus.model.vo.PermissionTreeVO;
import com.wtwd.campus.model.vo.ResultVO;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author zdl
 * @since 2021-06-08
 */
@Service
public class SysPermissionServiceImpl implements SysPermissionService {
    @Resource
    private SysPermissionMapper sysPermissionMapper;

    private List<Integer> ids = new ArrayList<>(100);

    /**
     * 为保证已生成的权限id不变,采用插入或更新的方式处理
     */
    @PostConstruct
    private void create() {
        ClassPathResource resource = new ClassPathResource("permission.json");
        JSONObject jsonData = null;
        if (resource.exists()) {
            try {
                jsonData = (JSONObject) JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, JSONObject.class,
                        // 自动关闭流
                        Feature.AutoCloseSource,
                        // 允许注释
                        Feature.AllowComment,
                        // 允许单引号
                        Feature.AllowSingleQuotes,
                        Feature.OrderedField
                );
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(jsonData.toJSONString());
        //清空权限表记录
        //sysPermissionMapper.clear();
        for (int i = 1; i <= jsonData.size(); i++) {
            JSONObject json = jsonData.getJSONObject(i + "");
            createChild(0, json);
        }
        //删除本次修改中不存在的
        sysPermissionMapper.deleteByNonId(ids);
    }


    private void createChild(Integer pid, JSONObject json) {
        json.put("pid", pid);
        Object children = json.get("children");
        if (pid == 0) {
            json.put("menuType", "1");
        } else {
            json.put("menuType", "2");
        }
        sysPermissionMapper.saveOrUpdate(json);
        ids.add(json.getInteger("id"));
        //插入数据并且返回主键
        if (children instanceof JSONArray) {
            JSONArray array = (JSONArray) children;
            //存在子节点继续遍历
            for (int i = 0; i < array.size(); i++) {
                createChild(json.getInteger("id"), array.getJSONObject(i));
            }
        } else if (children instanceof String) {
            // 插入 按钮类型的权限
            String s = (String) children;
            if ("".equals(s)) return;
            if (s.startsWith("-")) {
                s = "添加,删除,修改" + s.replace("-", "");
            }
            String[] split = s.split(",");
            //默认增删改
            for (String name : split) {
                JSONObject param = new JSONObject();
                param.put("menuType", "10");
                param.put("pid", json.getInteger("id"));
                param.put("name", name);
                sysPermissionMapper.saveOrUpdate(param);
                ids.add(param.getInteger("id"));
            }
            //批量插入或更新 无法保存正确返回所有主键
            //sysPermissionMapper.savePermissionBatch(params);
        }
    }

    @Override
    public ResultVO getAllPermissionTree(Integer type) {
        List<SysPermission> sysPermissions = sysPermissionMapper.listAllPermission();
        List<PermissionTreeVO> treeData = sysPermissions.stream().map(data -> {
            PermissionTreeVO treeVO = new PermissionTreeVO();
            treeVO.setId(data.getId());
            treeVO.setName(data.getName());
            if (type!=null){
                if (type== ManLanguageEnum.EN.getType()){
                    treeVO.setName(data.getEn());
                }
            }
            treeVO.setPid(data.getPid());
            treeVO.setMenuType(data.getMenuType());
            return treeVO;
        }).collect(Collectors.toList());
        return ResultVO.ok(TreeUtil.createTree(treeData));
    }
}
